package com.github.shiqiyue.myadmin.service;

import com.github.shiqiyue.myadmin.common.SessionConst;
import com.google.code.kaptcha.Producer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/***
 * kaptcha（验证码生成和验证）服务
 * @Author: shiqiyue
 * @Date: 创建于2018/4/18/018 10:58 
 **/
@Service
public class KaptchaService {

    @Autowired
    private Producer captchaProducer;

    /***
     * 获取图形验证码
     * @param type
     * @param httpSession
     * @param response
     * @throws IOException
     */
    public void get(int type, HttpSession httpSession, HttpServletResponse response) throws IOException {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        String capText = captchaProducer.createText();
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        // write the data out
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        // 根据不同的类型，写入对应的session中的属性
        httpSession.setAttribute(SessionConst.SESSION_CAPTCHA_BASE + type, capText);
    }

    /***
     * 验证图形验证码是否正确
     *
     * @param type
     * @param inputCapText
     * @param httpSession
     * @return
     */
    public boolean verify(int type, String inputCapText, HttpSession httpSession) {
        String sessionCapText = "";
        // 获取session中保存的图形验证码的值
        sessionCapText = (String) httpSession.getAttribute(SessionConst.SESSION_CAPTCHA_BASE + type);
        if (StringUtils.isNotBlank(sessionCapText) && sessionCapText.equalsIgnoreCase(inputCapText)) {
            return true;
        }
        return false;
    }
}
